// pages/home/opendoor/keyList/keyList.js
import {fetchData,resultJudge} from '../../../../utils/request'
import {getUserInfo} from '../../../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
  userId:"",
  userDoorKeys:[],
  show:false,
  qRCodeInfoVo:{},
  },
  showPopup() {
    this.setData({ show: true });
  },

  onClose() {
    this.setData({ show: false });
  },
  getQRCode(userId,doorKey){
    fetchData(`/base/door/getQRCode?userId=${userId}&doorKey=${doorKey}`,"","GET",res=>{
    let result= resultJudge(res,"data")
    this.setData({
        show:result.open,
        qRCodeInfoVo:result
    })
    if(!result.open){
        wx.showToast({
          title: result.message,
          icon:"error"
        })
    }
    })
    },
    openQRCode(e){
        let door_key=e.currentTarget.dataset.door_key
        this.getQRCode(this.data.userId,door_key)
    },
  addKey(){
      let that=this;
      // 在某个页面或组件中调用扫描二维码功能
wx.scanCode({
    success(res) {
      let doorKey=res.result// 扫描结果
      let userId=that.data.userId
      fetchData(`/base/key_user/bindKey?userId=${userId}&doorKey=${doorKey}`,"","GET",res=>{
         let result= resultJudge(res,"none")
         if(result==200){
             wx.showToast({
               title: '绑定成功！！',
               icon:"success"
             })
             that.getUserDoorKeys(that.data.userId)
         }else{
            wx.showToast({
                title: '绑定失败！！',
                icon:"error"
              })
         }
      })
    },
    fail(res) {
      console.log(res.errMsg); // 扫描失败的错误信息
    }
  });
  
  },
  backPage(){
      wx.navigateBack()
  },
  getUserDoorKeys(userId){
      fetchData(`/base/key_user/getUserDoorKeys/${userId}`,"","GET",res=>{
       let userDoorKeys=   resultJudge(res,"list")
       this.setData({
        userDoorKeys:userDoorKeys
       })
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
   let user= getUserInfo()
  this.setData({
      userId:user.userId
  })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  this.getUserDoorKeys(this.data.userId)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})